﻿using MediatR;
using RedDragon.Common.Domain.Purchase;
using RedDragon.Common.Infrastructure.Interface;
using RedDragon.ERP.ErroCodeEnum;
using T.Common.Domain.Common;

namespace RedDragon.ERP.API.Application.Commands.Purchases
{
    /// <summary>
    /// 获取所属项目信息
    /// </summary>
    public class SearchAffiliatedProjectHandler : IRequestHandler<SearchAffiliatedProjectCommand, Result>
    {
        /// <summary>
        /// 所属项目仓储
        /// </summary>
        private readonly IBaseRepository<AffiliatedProject> _affiliatedProjectRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchAffiliatedProjectHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="affiliatedProjectRepository"></param>
        /// <param name="logger"></param>
        public SearchAffiliatedProjectHandler(IBaseRepository<AffiliatedProject> affiliatedProjectRepository,
                                              ILogger<SearchAffiliatedProjectHandler> logger)
        {
            _affiliatedProjectRepository = affiliatedProjectRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取所属项目信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SearchAffiliatedProjectCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await _affiliatedProjectRepository.GetAll()).ToListAsync();
                if (query.Count > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "获取所属项目信息成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取所属项目信息异常" + ex.Message;
                _logger.LogError("获取所属项目信息异常" + ex.Message);
            }
            return result;
        }
    }
}
